using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Net;
using System.Globalization;
using System.Configuration;

namespace BarnBuddyClient
{
    public partial class Form1 : Form
    {
        private ArrayList bbData = null;
        private bool isNotifying = false;

        private string dataUrl;
        private string submitUrl;
        private int notifyInterval = 0;
        private int loadDataInterval = 0;
        private int notifyBefore = 0;
        private bool showExtraNotification = true;
        private string monitorBrowsers = "";

        private BBCapture bbcapture = null;

        private bool sendingData = false;

        public Form1()
        {
            InitializeComponent();

            
        }

        void bbcapture_OnFirstItemCapture()
        {
            //tmrSubmitData.Enabled = true;
            //tmrSubmitData.Start();
        }

        private void LoadData(string path)
        {
            this.bbData = new ArrayList();

            StreamReader s = File.OpenText(path);
            string read = null;
            int count = 0;
            while ((read = s.ReadLine()) != null)
            {
                count++;

                if (count >= 4)
                {
                    string[] lines = read.Split(',');

                    if (lines[0]!="") {
                        string strName = lines[0];
                        string strDate = lines[3];

                        try
                        {
                            DateTime date = Convert.ToDateTime(strDate);
                            BBItem item = new BBItem(strName, date);
                            this.bbData.Add(item);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                    }
                }

            }
            s.Close();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //this.LoadData("c:\\crops.csv");
            this.notifyInterval = Convert.ToInt32(ConfigurationSettings.AppSettings["notify_interval"].ToString());
            this.loadDataInterval = Convert.ToInt32(ConfigurationSettings.AppSettings["load_data_interval"].ToString());
            this.notifyBefore = Convert.ToInt32(ConfigurationSettings.AppSettings["notify_before"].ToString())/60;
            this.dataUrl = ConfigurationSettings.AppSettings["data_url"].ToString();
            this.submitUrl =  ConfigurationSettings.AppSettings["submit_url"].ToString();
            this.showExtraNotification = ConfigurationSettings.AppSettings["show_extra_notification"] == "1";
            this.monitorBrowsers = ConfigurationSettings.AppSettings["monitor_browsers"].ToString();

            this.LoadDataFromUrl(this.dataUrl);

            this.tmrNotify.Interval = this.notifyInterval * 1000;
            this.tmrNotify.Enabled = true;

            this.tmrLoadData.Interval = this.loadDataInterval * 1000;
            this.tmrLoadData.Enabled = true;

            this.checkEvent();
            this.Hide();

            bbcapture = new BBCapture(this.monitorBrowsers);
            bbcapture.OnFirstItemCapture += new BBCapture.OnFirstItemCaptureDelegate(bbcapture_OnFirstItemCapture);
            bbcapture.Start();


            if (this.showExtraNotification)
                notifyIcon1.ShowBalloonTip(100, "BarnBuddyClient", "...has just started", ToolTipIcon.Info);

        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (FormWindowState.Minimized == WindowState)
                Hide();
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            //Show();
            //WindowState = FormWindowState.Normal;
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {

        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (this.showExtraNotification)
                notifyIcon1.ShowBalloonTip(10000, "BarnBuddyClient", "Closing...", ToolTipIcon.Info);
            this.Close();
        }

        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            //notifyIcon1.ContextMenuStrip.Show((Control)notifyIcon1, new Point(0,0));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.checkEvent();
        }

        private void checkEvent()
        {
            checkEvent(this.notifyBefore);
        }

        private void checkEvent(int minutes)
        {
            DateTime currentTime = DateTime.Now;
            ArrayList upcoming = new ArrayList();
            string strMessage = "";

            if (this.bbData == null) return;
            foreach (BBItem itm in this.bbData)
            {
                TimeSpan diff = itm.time - currentTime;
                int remain = (int)diff.TotalSeconds;
                if (remain > 0 && remain <= minutes * 60)
                {
                    upcoming.Add(itm);
                    strMessage += itm.name + " (" + itm.plant + "): ";
                    if (remain > 120)
                        strMessage += diff.Minutes + " min "+diff.Seconds+" sec\n";
                    else
                        strMessage += (int)diff.TotalSeconds +" sec\n";
                }
            }
            if (upcoming.Count > 0)
            {
                this.notifyIcon1.ShowBalloonTip(1000, "Upcoming", strMessage, ToolTipIcon.Info);
            }
        }

        private void webBrowser1_FileDownload(object sender, EventArgs e)
        {

        }

        private void LoadDataFromUrl(string url)
        {
            if (this.showExtraNotification)
                notifyIcon1.ShowBalloonTip(1000, "Updating data", "...", ToolTipIcon.Info);

            try
            {
                DataRequest req = new DataRequest();

                string jsonText = req.loadUrl(url);

                ArrayList objList = (ArrayList)JSON.JsonDecode(jsonText);

                this.bbData = new ArrayList();
                DateTimeFormatInfo mysqlDTFI = new DateTimeFormatInfo();
                mysqlDTFI.ShortDatePattern = "yyyy-MM-dd HH:mm:ss";

                foreach (Hashtable obj in objList)
                {
                    BBItem item = new BBItem();
                    item.name = (string)obj["user_name"];
                    item.time = DateTime.Parse((string)obj["harvert_time"], mysqlDTFI);
                    item.plant = (string)obj["plant"];
                    item.price = Convert.ToInt32(obj["price"]);
                    this.bbData.Add(item);
                }

            }
            catch (Exception e)
            {
            }
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            checkEvent(60);
        }

        private void tmrLoadData_Tick(object sender, EventArgs e)
        {
            this.LoadDataFromUrl(this.dataUrl);
        }

        private void updateDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.LoadDataFromUrl(this.dataUrl);
        }

        private void tmrSubmitData_Tick(object sender, EventArgs e)
        {
            Console.WriteLine(DateTime.Now.ToLongTimeString());

            if (bbcapture.data.Count < 1 || sendingData) return;

            sendingData = true;

            if (this.showExtraNotification)
                notifyIcon1.ShowBalloonTip(100, "Send data", "Sending " + bbcapture.data.Count + " items", ToolTipIcon.Info);

            //end waiting cycle
            //tmrSubmitData.Enabled = false;
            //tmrSubmitData.Stop();

            string postData = "data=";
            postData += JSON.JsonEncode(bbcapture.data);
            bbcapture.data.Clear();

            DataRequest req = new DataRequest();
            try
            {
                string response = req.loadUrl(this.submitUrl, "POST", postData);

                //refresh with new data
                LoadDataFromUrl(this.dataUrl);

                Console.WriteLine(response);
                /*
                if (textBox1.InvokeRequired)
                {
                    setTextDelegate cb = new setTextDelegate(setText);
                    this.Invoke(cb, response);
                }
                else
                {
                    textBox1.Text = response;
                }
                 */
            }
            catch (Exception exception)
            {
                if (this.showExtraNotification)
                    notifyIcon1.ShowBalloonTip(1000, "Send data error", exception.Message, ToolTipIcon.Error);
            }

            sendingData = false;
        }
    }
}